package org.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.example.springboot.entity.Book;
import org.example.springboot.entity.Collection;
import org.example.springboot.entity.User;
import org.example.springboot.exception.ServiceException;
import org.example.springboot.mapper.BookMapper;
import org.example.springboot.mapper.CollectionMapper;
import org.example.springboot.util.JwtTokenUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 收藏服务类
 */
@Service
public class CollectionService {
    @Resource
    private CollectionMapper collectionMapper;
    
    @Resource
    private BookMapper bookMapper;
    
    /**
     * 添加收藏
     * @param bookId 图书ID
     * @return 收藏ID
     */
    @Transactional(rollbackFor = Exception.class)
    public Long addCollection(Long bookId) {
        // 获取当前用户ID
        User currentUser = JwtTokenUtils.getCurrentUser();
        if(currentUser == null) {
            throw new ServiceException("用户未登录！");
        }
        Long userId = currentUser.getId();



        // 检查图书是否存在
        Book book = bookMapper.selectById(bookId);
        if (book == null) {
            throw new ServiceException("图书不存在");
        }
        
        // 检查是否已收藏
        Collection existCollection = collectionMapper.selectOne(
            new LambdaQueryWrapper<Collection>()
                .eq(Collection::getUserId, userId)
                .eq(Collection::getBookId, bookId)
        );
        
        if (existCollection != null) {
            throw new ServiceException("已经收藏过该图书");
        }
        
        // 创建收藏记录
        Collection collection = new Collection();
        collection.setUserId(userId);
        collection.setBookId(bookId);
        
        if (collectionMapper.insert(collection) <= 0) {
            throw new ServiceException("收藏失败");
        }
        
        return collection.getId();
    }
    
    /**
     * 取消收藏
     * @param bookId 图书ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelCollection(Long bookId) {
        // 获取当前用户ID
        User currentUser = JwtTokenUtils.getCurrentUser();
        if(currentUser == null) {
            throw new ServiceException("用户未登录！");
        }
        Long userId = currentUser.getId();



        // 检查是否已收藏
        Collection collection = collectionMapper.selectOne(
            new LambdaQueryWrapper<Collection>()
                .eq(Collection::getUserId, userId)
                .eq(Collection::getBookId, bookId)
        );
        
        if (collection == null) {
            throw new ServiceException("未收藏该图书");
        }
        
        // 删除收藏记录
        if (collectionMapper.deleteById(collection.getId()) <= 0) {
            throw new ServiceException("取消收藏失败");
        }
    }
    
    /**
     * 检查用户是否已收藏图书
     * @param bookId 图书ID
     * @return 是否已收藏
     */
    public boolean isCollected(Long bookId) {
        // 获取当前用户ID
        User currentUser = JwtTokenUtils.getCurrentUser();
        Long userId = 0L;
        if(currentUser!=null) {
           userId = currentUser.getId();
        }



        
        // 查询是否存在收藏记录
        return collectionMapper.selectCount(
            new LambdaQueryWrapper<Collection>()
                .eq(Collection::getUserId, userId)
                .eq(Collection::getBookId, bookId)
        ) > 0;
    }
    
    /**
     * 获取用户收藏列表
     * @param currentPage 当前页
     * @param size 每页大小
     * @return 收藏图书分页列表
     */
    public Page<Book> getUserCollections(Integer currentPage, Integer size) {
        // 获取当前用户ID
        User currentUser = JwtTokenUtils.getCurrentUser();
        if(currentUser == null) {
            throw new ServiceException("用户未登录！");
        }
        Long userId = currentUser.getId();




        // 查询用户收藏的图书ID列表
        Page<Collection> collectionPage = collectionMapper.selectPage(
            new Page<>(currentPage, size),
            new LambdaQueryWrapper<Collection>()
                .eq(Collection::getUserId, userId)
                .orderByDesc(Collection::getCreateTime)
        );
        
        // 转换为图书列表
        Page<Book> bookPage = new Page<>(currentPage, size, collectionPage.getTotal());
        List<Book> books = collectionPage.getRecords().stream()
            .map(collection -> bookMapper.selectById(collection.getBookId()))
            .filter(book -> book != null)
            .toList();
        
        bookPage.setRecords(books);
        return bookPage;
    }
    
    /**
     * 获取用户收藏的所有图书ID
     * @param userId 用户ID
     * @return 图书ID列表
     */
    public List<Long> getUserCollectionBookIds(Long userId) {
        return collectionMapper.selectList(
            new LambdaQueryWrapper<Collection>()
                .eq(Collection::getUserId, userId)
                .select(Collection::getBookId)
        ).stream().map(Collection::getBookId).toList();
    }
} 